package cn.bas.core.web.exception;

import cn.bas.constants.ServiceExceptionEnum;
import cn.bas.core.exception.ServiceException;
import cn.bas.core.vo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;


@ControllerAdvice(basePackages = "cn.bas.controller")
public class GlobalExceptionHandler {
    // 获得logger对象
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 处理ServiceException
    /*
    @ExceptionHandler(value=指定异常.class)
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public CommonResult serviceExceptionHandler(ServiceException ex){
        logger.debug("[serviceExceptionHandler]",ex);
        return  CommonResult.error(ex.getCode(),ex.getMessage());
    }

    /*
    处理MissingServletRequestParameterException
     */
    @ResponseBody
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public CommonResult missingServletRequestParameterExceptionHandler(HttpServletRequest request,
                                                                       MissingServletRequestParameterException ex){
        logger.debug("[MissingServletRequestParameterException]",ex);
        return CommonResult.error(ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getCode(),
                ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getMessage());

    }

    /*
    处理其他异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public CommonResult exceptionHandler(HttpServletRequest request,Exception ex){
        logger.debug("[ExceptionHandler]",ex);
        return CommonResult.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
                ServiceExceptionEnum.SYS_ERROR.getMessage());
    }
}
